<?php

$di     = \application\units\Di::getInstance();
$params = [
    'pid'      => $di->request->params('pid'),
    'type'     => $di->request->params('type'),
    'path'     => $di->request->params('path'),
    'resource' => $di->request->params('resource'),
    'title'    => $di->request->params('title'),
    'icon'     => $di->request->params('icon', ''),
    'remark'   => $di->request->params('remark', ''),
    'badge'    => $di->request->params('badge', ''),
    'weigh'    => $di->request->params('weigh'),
    'status'   => $di->request->params('status'),
];
if (!ctype_digit($params['pid'])) throw new LogicException('Invalid param pid');
if (!in_array($params['type'], [1, 2])) throw new LogicException('Invalid param type');
if ('' == $params['path']) throw new LogicException('Invalid param path');
if ('' == $params['resource']) throw new LogicException('Invalid param resource');
if ('' == $params['title']) throw new LogicException('Invalid param title');
if (!ctype_digit($params['weigh'])) throw new LogicException('Invalid param weigh');
if (!in_array($params['status'], [0, 1])) throw new LogicException('Invalid param status');


if ($params['pid'] > 0) {
    $hasPid = $di->db->find('select * from admin_resource where type=1 and id=:id', [
        'id' => $params['pid'],
    ]);
    if (!$hasPid) throw new LogicException('pid菜单不存在');
}

$hasPath = $di->db->find('select * from admin_resource where path=:path', [
    'path' => $params['path'],
]);
if ($hasPath) throw new LogicException('路径已存在');

$hasResource = $di->db->find('select * from admin_resource where resource=:resource', [
    'resource' => $params['resource'],
]);
if ($hasResource) throw new LogicException('资源已存在');

$di->db->execute('insert into admin_resource(pid, type, path, resource, title, icon, remark, badge, weigh, status, create_time, update_time)
                      values (:pid, :type, :path, :resource, :title, :icon, :remark, :badge, :weigh, :status, :create_time, :update_time)', [
    'pid'         => $params['pid'],
    'type'        => $params['type'],
    'path'        => $params['path'],
    'resource'    => $params['resource'],
    'title'       => $params['title'],
    'icon'        => $params['icon'],
    'remark'      => $params['remark'],
    'badge'       => $params['badge'],
    'weigh'       => $params['weigh'],
    'status'      => $params['status'],
    'create_time' => date('Y-m-d H:i:s'),
    'update_time' => date('Y-m-d H:i:s'),
]);
$id = $di->db->lastInsertId();

return [
    'row' => [
        'id' => $id,
    ],
];